const express = require('express');
const bodyParser = require('body-parser');
const config = require('../config');
const webhookRoutes = require('./routes/webhook');

const app = express();

// 中间件配置
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 路由配置
app.use('/webhook', webhookRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '飞书机器人webhook服务器',
    version: '1.0.0',
    endpoints: {
      webhook: '/webhook/feishu',
      health: '/webhook/health'
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误'
  });
});

// 启动服务器
const PORT = config.server.port;
const HOST = config.server.host;

app.listen(PORT, HOST, () => {
  console.log(`🚀 飞书机器人webhook服务器已启动`);
  console.log(`📍 服务地址: http://${HOST}:${PORT}`);
  console.log(`🔗 Webhook端点: http://${HOST}:${PORT}/webhook/feishu`);
  console.log(`💚 健康检查: http://${HOST}:${PORT}/webhook/health`);
  console.log(`⏰ 启动时间: ${new Date().toISOString()}`);
});

module.exports = app; 